import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import StorageUtil from '../../utils/Storage.ts';
import { ThunkAction } from 'redux-thunk';
import { AnyAction } from 'redux';
import { defaultUserInfo } from '../../common/config.ts';

export interface IBeeperParams {
  queryType: number;
  latitude: string | number;
  longitude: string | number;
  provinceName: string;
  cityName: string;
  areaName: string;
}

interface IAppState {
  registerID: string;
  badge: number;
  userInfo: ILoginResponse;
  beeperId: number;
  recording: string;
  btnInformation?: IServerBtnListBtnList;
  beeperParams: IBeeperParams;
  shoppingCart: IProductInformation[];
}

const initialState: IAppState = {
  registerID: '',
  badge: -1,
  userInfo: defaultUserInfo,
  beeperId: 0,
  recording: '',
  beeperParams: { queryType: 1, latitude: '', longitude: '', provinceName: '', cityName: '', areaName: '' },
  shoppingCart: [],
};

const appSlice = createSlice({
  name: 'App',
  initialState,
  reducers: {
    updateUserInfo: (state, action: PayloadAction<ILoginResponse>) => {
      state.userInfo = action.payload;
      StorageUtil.load<ILoginResponse>('userInfo').then(async (res) => {
        if (res) await StorageUtil.save<ILoginResponse>('userInfo', { ...res, ...action.payload });
      });
    },
    updateBtnInformation: (state, action: PayloadAction<IServerBtnListBtnList>) => {
      state.btnInformation = action.payload;
    },
    updateBeeperID: (state, action: PayloadAction<number>) => {
      state.beeperId = action.payload;
    },
    updateRegisterID: (state, action: PayloadAction<string>) => {
      state.registerID = action.payload;
    },
    updateBadge: (state, action: PayloadAction<number>) => {
      state.badge = action.payload;
    },
    updateRecording: (state, action: PayloadAction<string>) => {
      state.recording = action.payload;
    },
    updateBeeperParams: (state, action: PayloadAction<IBeeperParams>) => {
      state.beeperParams = action.payload;
    },
    updateShoppingCart: (state, action: PayloadAction<{ type: 'add' | 'remove'; data: IProductInformation }>) => {
      const { type, data } = action.payload;
      const { shoppingCart } = state;
      const productIndex = shoppingCart.findIndex((item) => item.goodsId === data.goodsId);

      if (type === 'add') {
        if (productIndex !== -1) {
          // 如果商品已在购物车中，增加数量
          shoppingCart[productIndex].nums += 1;
        } else {
          // 如果商品不在购物车中，添加商品，初始数量为1
          shoppingCart.push({ ...data, nums: 1 });
        }
      } else if (type === 'remove') {
        if (productIndex !== -1) {
          if (shoppingCart[productIndex].nums > 1) {
            // 数量大于1时，减少数量
            shoppingCart[productIndex].nums -= 1;
          } else {
            // 数量为1时，直接移除商品
            shoppingCart.splice(productIndex, 1);
          }
        }
      }
    },
    updateShoppingCartSku: (state, action: PayloadAction<{ type: 'add' | 'remove'; data: IProductInformation }>) => {
      const { type, data } = action.payload;
      const { shoppingCart } = state;
      const productIndex = shoppingCart.findIndex((item) => item.goodsId === data.goodsId && item.sku === data.sku);
      const hasPackage = data.goodsType === 2 && shoppingCart.find((item) => item.goodsId === data.goodsId);
      if (type === 'add') {
        if (productIndex !== -1) {
          shoppingCart[productIndex].nums += data.nums;
        } else {
          // 如果是套餐产品 活动是不会算到每个规格，所以规格不一样但是每加一个同样的套餐时，maxNum -1
          if (hasPackage) {
            shoppingCart.forEach((item, index) => {
              if (item.goodsId === data.goodsId) {
                shoppingCart[index].active = { ...shoppingCart[index].active, maxNum: shoppingCart[index].active.maxNum - 1 };
              }
            });
            shoppingCart.push({ ...data, active: { ...data.active, maxNum: data.active.maxNum - shoppingCart.filter((item) => item.goodsId === data.goodsId).length } });
          } else {
            shoppingCart.push(data);
          }
        }
      } else if (type === 'remove') {
        if (productIndex !== -1) {
          if (shoppingCart[productIndex].nums > 1) {
            shoppingCart[productIndex].nums -= 1;
          } else {
            if (hasPackage) {
              shoppingCart.forEach((item, index) => {
                if (item.goodsId === data.goodsId) {
                  shoppingCart[index].active = { ...shoppingCart[index].active, maxNum: shoppingCart[index].active.maxNum + 1 };
                }
              });
            }
            shoppingCart.splice(productIndex, 1);
          }
        }
      }
    },
    updateShoppingCartHours: (state, action: PayloadAction<IProductInformation[]>) => {
      const newProducts = action.payload;
      newProducts.forEach((newProduct) => {
        const existingProduct = state.shoppingCart.find((item) => item.goodsId === newProduct.goodsId);
        // 替换 goodsHours
        if (existingProduct) {
          existingProduct.goodsHours = newProduct.goodsHours;
        }
      });
    },
    removeShoppingCart: (state, action: PayloadAction<number | undefined>) => {
      if (action.payload) {
        state.shoppingCart = state.shoppingCart.filter((item) => item.goodsId !== action.payload);
      } else {
        state.shoppingCart = [];
      }
    },
    initializeState: (state, action: PayloadAction<ILoginResponse>) => {
      return { ...state, userInfo: action.payload };
    },
  },
});

export const { updateUserInfo, updateBeeperID, updateRegisterID, initializeState, updateBadge, updateRecording, updateBtnInformation, updateBeeperParams, updateShoppingCart, removeShoppingCart, updateShoppingCartHours, updateShoppingCartSku } = appSlice.actions;

export default appSlice.reducer;

/**
 * 异步更新badge
 */
export const fetchInitialBadge = (): ThunkAction<void, IAppState, unknown, AnyAction> => async (dispatch) => {
  try {
    const badge = await StorageUtil.load<number>('badge');
    if (badge) {
      dispatch(updateBadge(badge));
    } else {
      dispatch(updateBadge(0));
    }
  } catch (error) {
    console.error('更新失败:', error);
  }
};

/**
 * 异步更新UserInfo
 */
export const fetchInitialUserInfo = (): ThunkAction<void, IAppState, unknown, AnyAction> => async (dispatch) => {
  try {
    const userInfo = await StorageUtil.load<ILoginResponse>('userInfo');
    if (userInfo) {
      dispatch(initializeState(userInfo));
    }
  } catch (error) {
    console.error('更新失败:', error);
  }
};

/**
 * 异步更新购物车
 */
export const fetchInitialShoppingCart = (): ThunkAction<void, IAppState, unknown, AnyAction> => async (dispatch) => {
  try {
    // const userInfo = await StorageUtil.load<ILoginResponse>('userInfo');
    // if (userInfo) {
    // dispatch(initializeState(userInfo));
    // }
  } catch (error) {
    console.error('更新失败:', error);
  }
};
